package com.qyhl.school.school.vlog;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.school.school.SchoolHomeActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.SingleChoiceDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolThemeBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

public class SchoolVlogFragment extends BaseFragment implements SchoolVlogContract.SchoolVlogView {
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.tag_recyclerview)
    RecyclerView tagRecyclerview;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R2.id.back_btn)
    ImageButton backBtn;
    @BindView(R2.id.title_name)
    ImageView title;

    private CommonAdapter<SchoolVlogBean> commonAdapter;

    private List<SchoolVlogBean> mDataList = new ArrayList<>();

    private CommonAdapter<SchoolThemeBean> tagCommonAdapter;

    private List<SchoolThemeBean> mTagList = new ArrayList<>();

    private SchoolVlogPresenter mPresenter;

    private int lastId = 0;

    private int lastBoost = 0;

    private String mVideoCoverPath;

    private String mVideoPath;

    /**
     * 视频选择
     */
    public static final int CHOOSE_VIDEO = 100;

    private boolean isFromHome;

    public void setFromHome(boolean fromHome) {
        isFromHome = fromHome;
    }

    public static SchoolVlogFragment newInstance(boolean isFrom) {
        SchoolVlogFragment fragment = new SchoolVlogFragment();
        fragment.setFromHome(isFrom);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_vlog_home, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SchoolVlogPresenter(this);

        if (isFromHome) {
            titleLayout.setBackgroundResource(R.drawable.school_title_bg);
            backBtn.setImageResource(R.drawable.btn_white_back_default);
            title.setImageResource(R.drawable.school_vlog_title_white);
        } else {
            titleLayout.setBackgroundResource(R.color.white);
            backBtn.setImageResource(R.drawable.btn_back_default);
            title.setImageResource(R.drawable.school_vlog_title_dark);
        }


        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        tagRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
        tagRecyclerview.setAdapter(tagCommonAdapter = new CommonAdapter<SchoolThemeBean>(getContext(), R.layout.item_school_vlog_home_tag, mTagList) {
            @Override
            protected void convert(ViewHolder holder, SchoolThemeBean schoolThemeBean, int position) {
                holder.setText(R.id.title, "#" + schoolThemeBean.getName() + "#");
                RoundedImageView cover = holder.getView(R.id.cover);

                Glide.with(SchoolVlogFragment.this)
                        .load(schoolThemeBean.getImageUrl())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);
            }
        });

        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.setAdapter(commonAdapter = new CommonAdapter<SchoolVlogBean>(getContext(), R.layout.item_school_vlog_home, mDataList) {
            @Override
            protected void convert(ViewHolder holder, SchoolVlogBean schoolVlogBean, int position) {
                holder.setText(R.id.nickName, schoolVlogBean.getAuthor().getNickName());
                if (schoolVlogBean.getTag() != null) {
                    holder.setText(R.id.tagName, "#" + schoolVlogBean.getTag().getName() + "#");
                }
                holder.setText(R.id.description, schoolVlogBean.getInfo());

                RoundedImageView cover = holder.getView(R.id.cover);
                RoundedImageView headCover = holder.getView(R.id.head_cover);

                Glide.with(SchoolVlogFragment.this)
                        .load(schoolVlogBean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                Glide.with(SchoolVlogFragment.this)
                        .load(schoolVlogBean.getAuthor().getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headCover);
            }
        });

        mPresenter.getTheme();
        mPresenter.getList(lastId, lastBoost);
    }


    @Override
    protected void setListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) mDataList);
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_VLOG_PLAY)
                        .withBundle("list", bundle)
                        .withInt("position", position)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        tagCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_VLOG_THEME_DETAIL)
                        .withInt("tagId", mTagList.get(position).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastId = 0;
                lastBoost = 0;
                mPresenter.getTheme();
                mPresenter.getList(lastId, lastBoost);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lastId = 0;
                lastBoost = 0;
                mPresenter.getTheme();
                mPresenter.getList(lastId, lastBoost);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(lastId, lastBoost);
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @Override
    public void setList(List<SchoolVlogBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        lastId = beanList.get(beanList.size() - 1).getId();
        lastBoost = beanList.get(beanList.size() - 1).getBoost();
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Override
    public void setTheme(List<SchoolThemeBean> beanList) {
        if (beanList != null && beanList.size() > 0) {
            mTagList.clear();
            if (beanList.size() < 5) {
                mTagList.addAll(beanList);
            } else {
                for (int i = 0; i < 4; i++) {
                    mTagList.add(beanList.get(i));
                }
            }
            tagCommonAdapter.notifyDataSetChanged();
        }
    }


    @OnClick({R2.id.more, R2.id.shoot_btn, R2.id.back_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            if (getActivity() instanceof SchoolHomeActivity) {
                ((SchoolHomeActivity) getActivity()).doFinish();
            } else if (getActivity() instanceof SchoolVlogActivity) {
                ((SchoolVlogActivity) getActivity()).doFinish();
            }
        } else if (id == R.id.more) {
            RouterManager.router(ARouterPathConstant.SCHOOL_VLOG_THEME_LIST);
        } else if (id == R.id.shoot_btn) {
            new SingleChoiceDialog.Builder(getContext()).setTitle("提示", R.color.global_black_lv2)
                    .addList(new String[]{"拍摄", "本地视频"})
                    .setCancelTextColor(R.color.global_base)
                    .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                        @Override
                        public void OnItemClick(String title, int position) {
                            switch (position) {
                                case 0:
                                    XXPermissions.with(getContext())
                                            .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA, Permission.RECORD_AUDIO)
                                            .request(new OnPermissionCallback() {
                                                @Override
                                                public void onGranted(List<String> permissions, boolean all) {
                                                    if (all) {
                                                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                                            @Override
                                                            public void login(boolean isLogin) {
                                                                if (isLogin) {
                                                                    if (StringUtils.isMi8()) {
                                                                        ARouter.getInstance()
                                                                                .build(ARouterPathConstant.SCHOOL_SHOOT2)
                                                                                .withString("cover", mVideoCoverPath)
                                                                                .withString("video", mVideoPath)
                                                                                .navigation();
                                                                    } else {
                                                                        ARouter.getInstance()
                                                                                .build(ARouterPathConstant.SCHOOL_SHOOT)
                                                                                .withString("cover", mVideoCoverPath)
                                                                                .withString("video", mVideoPath)
                                                                                .navigation();
                                                                    }
                                                                } else {
                                                                    showToast("尚未登录或登录已失效！", 4);
                                                                    RouterManager.routerLogin(getActivity(), 0);
                                                                }
                                                            }

                                                            @Override
                                                            public void error(String s) {

                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                    break;
                                case 1:
                                    XXPermissions.with(getContext())
                                            .permission(Permission.WRITE_EXTERNAL_STORAGE)
                                            .request(new OnPermissionCallback() {
                                                @Override
                                                public void onGranted(List<String> permissions, boolean all) {
                                                    if (all) {
                                                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                                            @Override
                                                            public void login(boolean isLogin) {
                                                                if (isLogin) {
                                                                    chooseVideo();
                                                                } else {
                                                                    showToast("尚未登录或登录已失效！", 4);
                                                                    RouterManager.routerLogin(getActivity(), 0);
                                                                }
                                                            }

                                                            @Override
                                                            public void error(String s) {

                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                    break;
                                default:
                                    break;
                            }
                        }
                    })
                    .show();
        }
    }

    /**
     * 选择视频
     */
    private void chooseVideo() {
        PictureSelector.create(SchoolVlogFragment.this)
                .openGallery(PictureMimeType.ofVideo())
                .imageSpanCount(4)
                .previewVideo(true)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .isCamera(false)
                .isZoomAnim(true)
                .compress(true)
                .videoMaxSecond(180)
                .videoMinSecond(2)
                .videoQuality(1)
                .recordVideoSecond(15)
                .forResult(CHOOSE_VIDEO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_VIDEO: {
                //视频选择
                List<LocalMedia> pic = PictureSelector.obtainMultipleResult(data);
                if (pic != null && pic.size() > 0) {
                    //视频路径
                    String path = pic.get(0).getPath();
                    getPicture(path);
                    mVideoPath = path;

                    ARouter.getInstance()
                            .build(ARouterPathConstant.SCHOOL_VLOG_UPLOAD)
                            .withString("cover", mVideoCoverPath)
                            .withString("video", mVideoPath)
                            .navigation();
                }
            }
            break;
            default:
                break;
        }
    }

    /**
     * 获取视频封面图
     */
    public void getPicture(String path) {
        File file = new File(path);
        //判断对象是否存在，不存在的话给出Toast提示
        if (file.exists()) {
            //提供统一的接口用于从一个输入媒体中取得帧和元数据
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(path);
            Bitmap bitmap = retriever.getFrameAtTime();
            String dirpath = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Pic;
            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString() + ".png";
            mVideoCoverPath = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Pic + File.separator + name;
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mVideoCoverPath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("生成封面图失败", INFO);
            }
        } else {
            showToast("视频路径不存在", INFO);
        }
    }


}
